import configparser
import os
import time
from datetime import timedelta
from gevent import pywsgi
import ast
from SQL.base_sql import DataBase
from flask import request,jsonify
from flask import Flask, render_template, make_response, session
from flask_cors import *

app = Flask(__name__)
app.debug = True
CORS(app, supports_credentials=True)
db = DataBase()
from MD5._MD5 import SM4Utils

# 配置sessions密钥
app.secret_key = 'cyq@1320!zlyj*'
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})


# 登录
@app.route('/api/v1/login', methods=['POST', 'GET'])
@cross_origin()
def login():  # 获取用户账号
    if request.method == 'POST':
        a = sm4.decryptData_ECB(request.values['msg'])
        # 字符串转字典
        DE_SM4 = ast.literal_eval(a)
        # # 拿到token令牌,并解密
        # token = sm4.decryptData_ECB(request.headers.get('token'))
        # EffectiveTime = time.strftime("%Y-%m-%d %H:%M:%S", token.split(':')[-1])  # 取出有效时间
        #
        # print(EffectiveTime)
        username = DE_SM4['name']
        password = DE_SM4['password']
        result = db.LoginSql(username, password)
        # 登录成功
        if result.get('status') == 0:
            # 登陆成功，保存session
            session[username] = username
            en_result = CreatToken(username + password)
            result['token'] = en_result
        response = make_response(result)
        # 设置响应请求头
        # response.headers["Access-Control-Allow-Origin"] = '*'  # 允许使用响应数据的域。也可以利用请求header中的host字段做一个过滤器。
        response.headers["Access-Control-Allow-Headers"] = "content-type"  # 允许的请求header
    return response


@app.route('/api/v1/UpdateInfo')
def UpdateInfo():  # 更新用户信息
    pass


@app.route('/api/v1/CyqRegister', methods=['POST', 'GET'])
def RegisterInfo():  # 注册用户信息
    if request.method == 'POST':
        _register_info = sm4.decryptData_ECB(request.values['msg'])
        # 字符串转字典
        DE_SM4 = ast.literal_eval(_register_info)
        result = db.RegisterSql(DE_SM4['newPwd'], DE_SM4['Nack'], DE_SM4['Email'])
    return result


# 登出
@app.route('/api/v1/logout')
def LogoutInfo():  # 用户退出登录
    if request.method == 'POST':
        u_name = sm4.decryptData_ECB(request.values['msg'])['account']
        return db.logout(u_name)


def CreatToken(recv_data: str):  # 根据用户请求登录生成token
    """
    return:通过返回的用户信息与当前时间戳生成token在两个小时内有效
    """
    # sm4 = SM4Utils()  # 实例化sm4加密
    token = sm4.encryptData_ECB(recv_data + ":" + str(time.time() + 7200))
    return token


if __name__ == '__main__':
    cf = configparser.ConfigParser()
    cf.read('config.ini')
    sm4 = SM4Utils()  # 实例化sm4加密
    app.run(
        host=cf.get('server', 'url'),
        port=int(cf.get('server', 'port')),
        # debug=True
    )
    # server = pywsgi.WSGIServer((cf.get('server', 'url'), int(cf.get('server', 'port'))), app)
    # server.serve_forever()
# pip freeze > requirements.txt
